<?php

namespace api\mobile;

use think\facade\Db;
use app\common\model\Mobile;

/**
 * 券妈妈[这家没跑了]
 * 
 * 接口文档：https://www.showdoc.com.cn/QmmMobileApi/6986444913565292
 */
class Quanmama extends BaseModel
{
    private $header = [
        'Content-Type: multipart/form-data',
    ];

    /**
     * 创建订单
     *
     * @params
     * sub_order_id 系统订单号
     * amount 充值金额
     * mobile 充值号码
     * 
     * $return  false/供应商订单号
     */
    public function create($order)
    {
        $url = $this->info['url'] . '/api/mobile';
        $params = [
            'type' => 'quanmama.mobile.order',
            'app_key' => $this->info['app_id'],
            'mobile' => $order['mobile'],
            'out_trade_no' => $order['sub_order_id'],
            'amount' => fen2yuan($order['amount']),
            'timestamp' => time(),
            'notify' => $this->notifyUrl,
            'isFast' => $order['order_type'] == 1 ? 0 : 1,
        ];
        $params['sign'] = $this->getSign($params);
        $res = curlPost($url, $params, $this->header, 5, true);
        $res = json_decode($res, true);

        $supplier_order_no = '';
        $remark = $res['msg'] ?? '';
        $returnCode = $res['code'] ?? 1100;
        switch ($returnCode) {
            case 0: // 成功
                $status = self::SUCCESS;
                $supplier_order_no = $res['data']['order_id'];
                break;
            case 1007: // 账户余额不足50元，请及时充值
            case 1010: // 账户余额不足，请及时充值
                $status = self::LACK_OF_MONEY;
                break;
            case 1001: // 参数错误
            case 1002: // 签名错误
            case 1004: // 订单不存在
            case 1005: // 只能充值50,100,200面额
            case 1006: // 用户不存在
            case 1008: // 维护中，请尝试其他金额
            case 1009: // 该接口只支持POST
            case 1011: // 时间间隔不能超过5天
            case 1012: // 最多支持同时查询50个订单号
            case 1015: // 慢充或快充权限未开通
            case 1016: // 下单次数超限
            case 1101: // 无权限
                $status = self::FAIL;
                break;
            case 1013: // 虚拟号码暂不支持充值
            case 1014: // 携号转网暂不支持充值
                $status = self::RECHARGE_FAIL;
                break;
            case 1100: // 系统异常，请稍后再试
                $status = self::NEED_RETRY;
                break;
            case 1003: // 订单已存在
            default:
                $status = self::NEED_CONFIRM;
                break;
        }

        return compact('status', 'supplier_order_no', 'remark');
    }

    /**
     * 查询余额
     * 
     * 单位：分
     */
    public function queryAmount()
    {
        $url = $this->info['url'] . '/api/mobile';
        $params = [
            'type' => 'quanmama.mobile.balance',
            'app_key' => $this->info['app_id'],
            'timestamp' => time(),
        ];
        $params['sign'] = $this->getSign($params);
        $res = curlPost($url, $params, $this->header);
        $res = json_decode($res, true);
        if (!isset($res['data']['balance'])) {
            $this->error = $res['msg'] ?? '查询频繁';
            return false;
        }
        return yuan2fen($res['data']['balance']);
    }

    /**
     * 订单查询
     */
    public function query($orderId)
    {
        $url = $this->info['url'] . '/api/mobile';
        $params = [
            'type' => 'quanmama.mobile.order.query',
            'app_key' => $this->info['app_id'],
            'out_trade_no' => $orderId,
            'timestamp' => time(),
        ];
        $params['sign'] = $this->getSign($params);
        $res = curlPost($url, $params, $this->header);
        $res = json_decode($res, true);
        return $res;
    }

    /**
     * 查询运营商、携号转网、面额维护等信息
     */
    public function phoneInfo($mobile)
    {
        $url = $this->info['url'] . '/api/mobile';
        $params = [
            'app_key' => $this->info['app_id'],
            'type' => 'quanmama.mobile.phone.info',
            'timestamp' => time(),
            'phoneNo' => $mobile,
            'amount' => '',
            'isFast' => '',
        ];
        $params['sign'] = $this->getSign($params);
        $res = curlPost($url, $params, $this->header);
        $res = json_decode($res, true);
        return $res;
    }

    /**
     * 生成签名
     */
    public function getSign($params)
    {
        if (isset($params['sign'])) {
            unset($params['sign']);
        }
        ksort($params);
        $str = '';
        foreach ($params as $k => $v) {
            if ($v !== '') {
                $str .= $k . '=' . $v . '&';
            }
        }
        $str .= 'app_secret=' . $this->info['app_secret'];
        return strtolower(md5($str));
    }

    /**
     * 订单回调
     */
    public function notify($params)
    {
        $insert = [
            'sub_order_id' => $params['out_trade_no'] ?? '',
            'params' => json_encode($params, JSON_UNESCAPED_UNICODE),
            'result' => 'SUCCESS'
        ];

        $sign = $params['sign'] ?? '';
        $checkSign = $this->getSign($params);
        if ($sign !== $checkSign) {
            $insert['result'] = '验签失败';
            Db::name('mobile_notify')->insert($insert);
            return $insert['result'];
        }

        $order = Db::name('mobile_order')
            ->where('sub_order_id', $params['out_trade_no'])
            ->where('mobile_supplier_id', $this->info['id'])
            ->where('mobile', $params['mobile'])
            ->find();
        if (empty($order)) {
            $insert['result'] = '订单不存在';
            Db::name('mobile_notify')->insert($insert);
            return $insert['result'];
        }

        if (in_array($order['supplier_status'], [3, 4, 99])) {
            // if ($order['supplier_status'] == 3) {
            $insert['result'] = '已经成功过';
            Db::name('mobile_notify')->insert($insert);
            return 'SUCCESS';
        }

        if ($order['supplier_status'] != 2) {
            $insert['result'] = '订单状态有误：' . $order['supplier_status'];
            Db::name('mobile_notify')->insert($insert);
            return $insert['result'];
        }

        $amount = fen2yuan($order['amount']);
        if ($amount != $params['amount']) {
            $insert['result'] = '订单金额不一致：' . $amount . ' -- ' . $params['amount'];
            Db::name('mobile_notify')->insert($insert);
            return $insert['result'];
        }

        // 供应商订单状态：1订单未创建 2订单已创建 3充值成功 4充值失败
        // 0表示充值中; 1表示已充值; 2表示充值失败;
        $supplierStatusMap = [
            0 => 2, // 0充值中 --> 2订单已创建
            1 => 3, // 1已充值 --> 3充值成功
            // 2 => 4, // 2充值失败 --> 4充值失败
            2 => 99, // 2充值失败 --> 充值失败，等待重试
            3 => 5, // 3部分充值成功 --> 5部分充值成功
        ];
        $supplierStatus = $supplierStatusMap[$params['status']] ?? 2;
        if ($order['supplier_status'] == $supplierStatus) {
            Db::name('mobile_notify')->insert($insert);
            return 'SUCCESS';
        }
        $update = [
            'supplier_order_no' => $params['order_id'],
            'supplier_status' => $supplierStatus,
        ];
        if ($supplierStatus == 99) {
            // $update['refund_status'] = 2;   // 充值失败，退款
            $order['notify_url'] = '';  // 失败通知先不发
        }
        if (!empty($params['finish_time'])) {
            $update['finish_time'] = strtotime($params['finish_time']);
        }

        Db::name('mobile_notify')->insert($insert);

        Db::startTrans();
        try {
            // 如果是返佣模式，将订单结算方式改成待结算
            if ($supplierStatus == 3 && $order['settle_type'] == SETTLE_TYPE_PROFIT) {
                if ($order['profit'] == 0) {
                    $update['settle_status'] = 3;
                } elseif ($order['settle_status'] == 1) {
                    $update['settle_status'] = 2;
                }
            }

            Mobile::handleNotify($order, $update);

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();

            $insert['result'] = '订单更新失败' . $order['id'] . '。' . $e->getMessage();
            Db::name('mobile_notify')->insert($insert);
            return $insert['result'];
        }

        return 'SUCCESS';
    }
}
